package com.czm.art_light.manager.mq.producer;

import com.czm.art_light.constant.AmqpConsts;
import com.czm.art_light.param.request.ArtWorkESReqDto;
import com.czm.art_light.util.JsonUtil;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.Jar;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.Map;

/**
 * AMQP 消息生产者类
 */
@Component
@RequiredArgsConstructor
public class AmqpMsgProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Value("${spring.amqp.enabled:false}")
    private boolean amqpEnabled;

    /**
     * 发送艺术作品ID改变ES中的信息
     */
    public void sendArtworkChangeMsg(ArtWorkESReqDto artWorkESReqDto) {
        if (amqpEnabled) {
            String message = JsonUtil.objToJson(artWorkESReqDto);
            sendAmqpMessage(rabbitTemplate, AmqpConsts.artWorksMq.ART_WORK_INFO_CHANGE_EXCHANGE, null, message);
        }
    }

    private void sendAmqpMessage(RabbitTemplate rabbitTemplate, String exchange, String routingKey,
        Object message) {
        //SpringAMQP发出的任何消息都是持久化
        // 如果在事务中则在事务执行完成后再发送，否则可以直接发送
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager.registerSynchronization(
                new TransactionSynchronization() {
                    @Override
                    public void afterCommit() {
                        rabbitTemplate.convertAndSend(exchange, routingKey, message);
                    }
                });
            return;
        }
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
    }

}
